package wc

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/context"
	"gopkg.in/mgo.v2/bson"
	"io/ioutil"
	"main/database"
	"main/env"
	"main/protos"
	"net/http"
	"net/url"
	"sync"
	"time"
)

// NewWork 禁止重定向的HTTPClient
func NewWorker() *http.Client {
	return &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }}
}

func NewReq(method, url string, ) *http.Request {
	var req *http.Request
	req, _ = http.NewRequest(method, url, nil)
	return req
}

var Workers = &sync.Pool{New: func() interface{} {
	return NewWorker()
}}

func init() {
	// 初始化
	Workers.Put(Workers.New())
}

// GetTable获取课程表
func GetTable(ctx *context.Context) {
	openid := ctx.Input.Header("openid")
	if openid == "" {
		Response(ctx, 0, "openid is empty", nil)
		return
	}

	// 从boltdb中获取内容
	var res ResCode2Session
	ds := database.NewSessionStore()
	defer ds.Close()
	con := ds.C(database.DBUsers)
	if err := con.Find(bson.M{"openid": openid}).One(&res); err != nil {
		if err.Error() == database.GetErrNotFound().Error() {
			Response(ctx, 0, "user not found", nil)
			return
		} else {
			Response(ctx, 0, err.Error(), nil)
			return
		}
	}

	var bm protos.BaseMessage
	param := url.Values{}
	param.Add("func", "course")
	param.Add("union_id", res.UnionID)

	URL := fmt.Sprintf("%sfunc?%s", env.AuthServer, param.Encode())
	req := NewReq("GET", URL)
	c := Workers.Get().(*http.Client)
	defer Workers.Put(c)
	resp, err := c.Do(req)
	if err != nil {
		Response(ctx, 0, err.Error(), nil)
		return
	}
	defer resp.Body.Close()

	bytebm, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		Response(ctx, 0, err.Error(), nil)
		return
	}
	err = bm.XXX_Unmarshal(bytebm)
	if err != nil {
		Response(ctx, 0, err.Error(), nil)
		return
	}

	if bm.Type == "course" {
		ctx.ResponseWriter.Write(bm.Data)
		return
	}

	Response(ctx, 0, string(bm.Data), nil)
	return

}

func Rate(ctx *context.Context) {
	dt := ctx.Request.Body
	content, err := ioutil.ReadAll(dt)
	if err != nil {
		Response(ctx, 0, fmt.Sprintf("评分失败，请重试，%s", err.Error()), nil)
		return
	}
	var c2s ResCode2Session
	session := ctx.Request.Header.Get("session")
	ds := database.NewSessionStore()
	defer ds.Close()
	con := ds.C(database.DBUsers)
	_ = con.Find(bson.M{"session": session}).One(&c2s)

	rate := make(map[string]interface{}, 5)

	err = json.Unmarshal(content, rate)
	if err != nil {
		Response(ctx, 1, err.Error(), nil)
		return
	}
	rate["union_id"] = c2s.UnionID

	_ = con.Insert(rate)
	Response(ctx, 1, "ok", nil)
	return
}

func GetRate(ctx *context.Context) {

	ds := database.NewSessionStore()
	defer ds.Close()
	con := ds.C(database.DBRates)
	var res []interface{}
	con.Find(nil).All(&res)
	Response(ctx, 1, "ok", res)
	return
}
